// StatusCollection.cs
//

namespace ServiceAdmin.Status
{
    using ServiceAdmin;
	using ServiceAdmin.Config;
    using System;
    using System.Collections;
    using System.ServiceProcess;

    /// <summary>
    /// Summary description for StatusCollection.
    /// </summary>
    public class StatusCollection : ICollection
    {
        private ServiceStatus[]	_status			= null;
        private GuiHandler		_handler		= null;
		private	ServiceControl	_control		= null;
		private ServiceStatus	_currentStatus	= null;
		private ServiceStatus	_defaultStatus	= null;


        public int Count
        {
            get { return _status.Length; }
        }


        public bool IsSynchronized
        {
            get { return true; }
        }


        public object SyncRoot
        {
            get { return this; }
        }


		public GuiHandler Handler
		{
			get { return _handler; }
		}


		public ServiceControl Control
		{
			get { return _control; }
		}


		public ServiceStatus CurrentStatus
		{
			get { return _currentStatus; }
		}


        public ServiceStatus this[ServiceControllerStatus status]
        {
            get
            {
                for (int i = 0; i < _status.Length; ++i)
                {
                    ServiceStatus currentStatus = _status.GetValue(i) as ServiceStatus;

                    if (currentStatus.Status == status)
                    {
                        return currentStatus;
                    }
                }
                return _defaultStatus;
            }
        }


        /// <summary>
        /// Creates a new instance of StatusCollection
        /// </summary>
        public StatusCollection(GuiHandler handler, ServiceControl control)
        {
			_status = new ServiceStatus[] {
			    new Default(this),
				new Stopped(this),
				new Running(this)
			};

			if (_status.Length > 0)
			{
				_defaultStatus = _status[0];
				_currentStatus = _defaultStatus;
			}

            _handler	= handler;
			_control	= control;
        }


		public void SetStatus(ServiceControllerStatus status)
		{
			ServiceStatus newStatus = this[status];

			if (newStatus != null)
			{
				_currentStatus = newStatus;
				_currentStatus.OnActivate();
			}
		}


        public IEnumerator GetEnumerator()
        {
            return _status.GetEnumerator();
        }


        public void CopyTo(Array array, int index)
        {
            _status.CopyTo(array, index);
        }
    }
}